package com.aiju.cash.ui.multiple_shops.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Shop;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.EnterApi;
import com.aiju.cash.core.api.ShopApi;
import com.aiju.cash.core.api.ShopManagetApi;
import com.aiju.cash.core.event.LimitsEvent;
import com.aiju.cash.ui.enter.AdressActivity;
import com.aiju.cash.ui.enter.CheckInActivity;
import com.aiju.cash.ui.enter.entity.EnterShopInfo;
import com.aiju.cash.ui.main.entity.ShopListEvent;
import com.aiju.cash.ui.multiple_shops.en.ShopManagerListType;
import com.aiju.cash.util.GsonHelper;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.utils.CheckUtil;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.layout.SettingItemEditView;
import com.aiju.widgit.layout.SettingItemTextView;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

import static com.aiju.cash.ui.enter.CheckInActivity.ADDRESS;

/**
 * @author: 佐为
 * @date: 2017-06-12 15:40
 * @version: V1.0
 * @Description: 新增普通门店
 */
public class ShopAddOrInfoActivity extends BaseTitleActivity {

    public static final int SHOW_ADD = 0;//新增门店
    public static final int SHOW_KOUBEI = 1;//口碑信息
    public static final int SHOW_COMMON = 2;//普通信息

    private int showType;

    private SettingItemEditView storeNameEditView, shopPhoneView;
    private SettingItemTextView addressTextView, typeTextView;

    private String shopName = "", contactNumber = "", shopType = "";
    private String code_name = "", province_code = "", city_code = "", district_code = "", address = "", longitude = "", latitude = "";

    private Shop mShop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_shop_info);
        storeNameEditView = (SettingItemEditView) findViewById(R.id.set_store_name);
        storeNameEditView.getleftView().setText(Html.fromHtml("门店名称<font color='#ec4545'>*</font>"));
        storeNameEditView.getRightView().setHint("请填写");

        storeNameEditView.setEditable(true);
        addressTextView = (SettingItemTextView) findViewById(R.id.set_store_adress);
        typeTextView = (SettingItemTextView) findViewById(R.id.set_store_type);
        shopPhoneView = (SettingItemEditView) findViewById(R.id.set_store_phone);
        shopPhoneView.getRightView().setHint("座机号请填写“区号-电话”，如：010-12345678");
        shopPhoneView.getRightView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
        shopPhoneView.setEditable(true);

        //地址
        findViewById(R.id.set_store_adress).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentAdress = new Intent(ShopAddOrInfoActivity.this, AdressActivity.class);
                intentAdress.putExtra("codeName", code_name);
                intentAdress.putExtra("province_code", province_code);
                intentAdress.putExtra("city_code", city_code);
                intentAdress.putExtra("district_code", district_code);
                intentAdress.putExtra("address", address);
                intentAdress.putExtra("longitude", longitude);
                intentAdress.putExtra("latitude", latitude);
                startActivityForResult(intentAdress, ADDRESS);
            }
        });

        showType = getIntent().getIntExtra("showType", 0);
        if (showType == SHOW_COMMON) {
            setCenterTitle("查看普通店铺信息");
            getShopInfo();
        } else if (showType == SHOW_KOUBEI) {
            setCenterTitle("查看口碑门店信息");
            mAiJuTitleBarView.getRightTextView().setVisibility(View.GONE);
            storeNameEditView.setEditable(false);
            storeNameEditView.getRightView().setTextColor(Util.getColor(R.color.color_999999));
            shopPhoneView.setEditable(false);
            shopPhoneView.getRightView().setTextColor(Util.getColor(R.color.color_999999));
            addressTextView.setOnClickListener(null);
            addressTextView.getRightView().setTextColor(Util.getColor(R.color.color_999999));
            addressTextView.getRightView().setCompoundDrawables(null, null, null, null);
            findViewById(R.id.set_store_ob_info).setVisibility(View.VISIBLE);
            findViewById(R.id.set_store_ob_info).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new EnterApi(mDialogHelper).getShopInfoByStoreId(mShop.getStoreId(), new SimpleHttpCallback() {
                        @Override
                        protected void onDataSuccess(String data) {
                            EnterShopInfo shopInfo = GsonHelper.convertEntity(data, EnterShopInfo.class);
                            Intent intent1 = new Intent(ShopAddOrInfoActivity.this, CheckInActivity.class);
                            intent1.putExtra("enterShopInfo", shopInfo);
                            startActivity(intent1);
                        }
                    });
                }
            });
            getShopInfo();
        } else {
            setCenterTitle("新增普通门店");
            shopType = getIntent().getStringExtra("shopType");//店铺类型：直营 加盟
            typeTextView.setRightText(shopType);
            findViewById(R.id.set_store_clerk).setVisibility(View.GONE);
            findViewById(R.id.btn_link_goods).setVisibility(View.GONE);
            findViewById(R.id.btn_shop_permission).setVisibility(View.GONE);
        }
        mAiJuTitleBarView.setRightTitle("保存");
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showType == SHOW_ADD) {
                    addShop();
                }
                if (showType == SHOW_COMMON) {
                    updataShop();
                }
            }
        });


        //查看店员
        findViewById(R.id.set_store_clerk).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShopAddOrInfoActivity.this, ClerkActivity.class);
                intent.putExtra("shop", mShop);
                startActivity(intent);
            }
        });
        //关联商品
        findViewById(R.id.btn_link_goods).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShopAddOrInfoActivity.this, RelationGoodActivity.class);
                intent.putExtra("storeId", mShop.getStoreId());
                startActivity(intent);
            }
        });
        //配置权限
        findViewById(R.id.btn_shop_permission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShopAddOrInfoActivity.this, ShopLimitsActivity.class);
                intent.putExtra("shop", mShop);
                startActivity(intent);
            }
        });

        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(LimitsEvent event) {
                getShopInfo();
            }
        });
    }

    /**
     * 请求店铺信息
     */
    private void getShopInfo() {
        mShop = (Shop) getIntent().getSerializableExtra("shop");
        mDialogHelper.showLoadingProgressDialog();
        new ShopApi().get(mShop.getId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson json = new DataJson(response);
                if (json.isSuccess()) {
                    mShop = GsonHelper.convertEntity(json.getData().toString(), Shop.class);
                    setShowInfo();
                } else {
                    T.ToastShort(json.getMsg());
                }
            }
        });
    }

    /**
     * 显示门店信息
     */
    private void setShowInfo() {
        storeNameEditView.setRightText(mShop.getShopName());
        ((EditText) storeNameEditView.getRightView()).setSelection(mShop.getShopName().length());
        addressTextView.setRightText(mShop.getCodeName() + mShop.getAddressDetail());
        shopPhoneView.setRightText(mShop.getContactNumber());
        typeTextView.setRightText(mShop.getShopTypeString());

        shopType = mShop.getShopTypeString();
        code_name = mShop.getCodeName();
        address = mShop.getAddressDetail();
        longitude = mShop.getLongitude();
        latitude = mShop.getLatitude();
        province_code = mShop.getProvinceCode();
        city_code = mShop.getCityCode();
        district_code = mShop.getDistrictCode();

        if (!mShop.getShopType().equals("0")) {
            findViewById(R.id.btn_link_goods).setVisibility(View.VISIBLE);
            //findViewById(R.id.btn_shop_permission).setVisibility(View.GONE);
        }
    }


    /**
     * 添加门店
     */
    private void addShop() {
        if (!checkShopInfo()) {
            return;
        }
        final String type = shopType.equals("直营店") ? "1" : "2";
        new ShopManagetApi(mDialogHelper).saveShop(shopName, province_code, city_code, district_code,
                address, code_name, longitude, latitude, contactNumber, type, new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        T.ToastShort("添加店铺成功");
                        Intent intent = new Intent(ShopAddOrInfoActivity.this, ShopManagerActivity.class);
                        Bundle b = new Bundle();
                        b.putSerializable(ShopManagerActivity.FROM, ShopManagerListType.SHOPMANAGER);
                        intent.putExtras(b);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                        if (!mUser.isHavaDirectSales() && "1".equals(type)) {
                            EventCenter.getInstance().post(new ShopListEvent());
                        }
                    }
                });
    }

    /**
     * 更新店铺
     */
    private void updataShop() {
        if (!checkShopInfo()) {
            return;
        }
        String type = shopType.equals("直营店") ? "1" : "2";
        new ShopManagetApi(mDialogHelper).updateShop(mShop.getId(), shopName, province_code, city_code, district_code,
                address, code_name, longitude, latitude, contactNumber, type, new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        T.ToastShort("修改店铺成功");
                        Intent intent = new Intent(ShopAddOrInfoActivity.this, ShopManagerActivity.class);
                        Bundle b = new Bundle();
                        b.putSerializable(ShopManagerActivity.FROM, ShopManagerListType.SHOPMANAGER);
                        intent.putExtras(b);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                });
    }

    /**
     * 检查店铺信息
     *
     * @return
     */
    private boolean checkShopInfo() {
        shopName = storeNameEditView.getRightText();
        contactNumber = shopPhoneView.getRightText();
        if (TextUtils.isEmpty(shopName)) {
            T.ToastShort("请填写门店名称");
            return false;
        }
        if (!CheckUtil.checkNickName(shopName)) {
            T.ToastShort("门店名称仅支持不超过15个字符的汉字、数字、英文及下划线");
            return false;
        }

        if (!TextUtils.isEmpty(contactNumber)) {
            if (!CheckUtil.isMultiplePhone(contactNumber)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == ADDRESS) {
            code_name = data.getStringExtra("codeName");
            address = data.getStringExtra("address");
            addressTextView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
            addressTextView.setRightText(code_name + address);

            longitude = data.getStringExtra("longitude");
            latitude = data.getStringExtra("latitude");
            province_code = data.getStringExtra("province_code");
            city_code = data.getStringExtra("city_code");
            district_code = data.getStringExtra("district_code");
            L.d("地址：" + latitude + longitude + code_name + address + province_code + city_code + district_code);
        }
    }
}
